//
//  ViewController.m
//  03.16-20202
//
//  Created by student on 16/3/16.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,strong)NSMutableArray *list;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@end

@implementation ViewController


-(NSMutableArray *)list
{
    if (_list==nil) {
        _list=[NSMutableArray array];
        
        NSUserDefaults *d=[NSUserDefaults standardUserDefaults];
        
        NSArray *arr=[d objectForKey:@"log"];
        if (arr!=nil) {
            _list=[arr mutableCopy];
        }
        
    }
    return _list;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self print];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(operate:) name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(operate:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(operate:) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(operate:) name:UIApplicationDidBecomeActiveNotification object:nil];
    
}

-(void)operate:(NSNotification *)sender
{

    NSDate *date=[NSDate date];
    NSDateFormatter *f=[[NSDateFormatter alloc]init];
//    f.dateStyle=NSDateFormatterNoStyle;
//    f.timeStyle=NSDateFormatterShortStyle;
    [f setDateFormat:@"HH:mm:ss"];
    NSString *str= [f stringFromDate:date];
    [self.list insertObject:[NSString stringWithFormat:@"%@ %@",str,[self chooseActive:sender]] atIndex:0];
    [self saveData];
    [self print];
    
}
-(void)saveData
{
    NSUserDefaults *d=[NSUserDefaults standardUserDefaults];
    
    [d setObject:self.list forKey:@"log"];
    [d synchronize];
}
-(NSString *)chooseActive:(NSNotification *)sender
{
   
    NSString *str=[NSString string];
    if ([sender.name isEqualToString:UIApplicationWillResignActiveNotification]) {
        str= @"将取消活动";
    }
    else if ([sender.name isEqualToString:UIApplicationDidEnterBackgroundNotification]) {
        str= @"已经进入后台";
    }
   else if ([sender.name isEqualToString:UIApplicationWillEnterForegroundNotification]) {
        str= @"将进入前台";
    }
    else if ([sender.name isEqualToString:UIApplicationDidBecomeActiveNotification ]) {
        str= @"已经激活";
    }
    return str;
    
}
-(void)print
{
    NSMutableString *str=[NSMutableString string];
    for (NSString *s in self.list) {
        
        [str appendString:s];
        [str appendString:@"\n"];
    }
    self.textView.text=str;
}

@end
